<?php

namespace App\Http\Controllers\Admin;

use App\Models\ServiceNotice;
use App\Models\ServiceNoticeSendLog;
use App\Models\UserInfo;
use App\Validate\ServiceNoticeValidate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 服务提醒通知
 * Class ServiceNotice
 * @package app\api\controller
 */
class ServiceNoticeController extends CommonController
{
    protected $model;
    protected $validate;


    public function __construct()
    {
        parent::__construct();
        $this->model = new ServiceNotice();
        $this->validate = new ServiceNoticeValidate();
    }
    /**
     * 服务提醒通知列表
     * @param node 是否批量推送  0全部   1 批量推送  ， 2 微信限制  3 读者证号限制
     * @param start_time 推送开始时间
     * @param end_time 推送结束时间
     * @param page 页数  默认为 1
     * @param limit 条数
     */
    public function lists()
    {
        $node = $this->request->node;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $data = $this->model->lists($node, $start_time, $end_time, $limit);

        if ($data['data']) {
            $data['data'] = $this->addSerialNumber($data['data'], $page, $limit);
            $data = $this->disPageData($data);
            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 详情
     * @param id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $data = $this->model->detail($this->request->id);

        if ($data) {
            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 服务提醒通知 添加
     * @param node 是否批量推送   1 批量推送  2 微信限制  3 读者证号限制
     * @param content 内容      必传  最大 100 字
     * @param type_name 服务类型   必传  最大 50 字
     * @param start_time 开始时间  年月日形式  YYYY-mm-dd
     * @param end_time 结束时间   年月日形式  YYYY-mm-dd
     * @param wechat_id 微信昵称id  多个逗号拼接
     * @param account_id 读者证号  多个逗号拼接
     * @param remark 备注     可选  最大 150 字
     * @param link 链接    可选  最大 120 字
     * @param is_send  1 立即发送   2 后续发送
     */
    public function add()
    {
        if (config("other.is_send_wechat_temp_info") !== true) {
            return $this->returnApi(202, '此功能未开通，请联系管理员进行处理！');
        }
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check(array_filter($this->request->all())))  //因为有些是可选参数，如果为空，内置验证也要验证，所以排除掉空数据
        {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $condition[] = ['node', '=', $this->request->node];
        $condition[] = ['type_name', '=', $this->request->type_name];
        $is_exists = $this->model->nameIsExists($this->request->content, 'content');

        if ($is_exists) {
            return $this->returnApi(202, "该内容已存在");
        }

        if ($this->request->node == 2 && empty($this->request->wechat_id)) {
            return $this->returnApi(202, '请选择需要推送的微信昵称！');
        }
        if ($this->request->node == 3 && empty($this->request->account_id)) {
            return $this->returnApi(202, '请选择需要推送的读者证号！');
        }

        set_time_limit(500); // 设置执行不超时

        if ($this->request->end_time) {
            $time = trim($this->request->start_time) . '~' . trim($this->request->end_time);
        } else {
            $time = trim($this->request->start_time);
        }
        $data = $this->request->all();
        unset($data['start_time']);
        unset($data['end_time']);
        $data['type_name'] = addslashes(trim($this->request->type_name));
        $data['content'] = addslashes(trim($this->request->content));
        $data['remark'] = addslashes(trim($this->request->remark));
        $data['link'] = addslashes(trim($this->request->link));
        $data['time'] = $time;
        $data['wechat_id'] = $this->request->node == 2 ? str_replace('，', ',', trim($this->request->wechat_id)) : '';
        $data['account_id'] = $this->request->node == 3 ? str_replace('，', ',', trim($this->request->account_id)) : '';
        $data['manage_id'] = request()->manage_id;

        DB::beginTransaction();
        try {
            $this->model->add($data);
            if ($this->request->is_send == 1) {
                $userInfoModel = new UserInfo();
                $user_info_arr = $userInfoModel->getUserInfoByWechatAccountId($data['wechat_id'], $data['account_id']);
                $user_id = array_column($user_info_arr, 'id');
                $user_id = join(',', $user_id);
                $this->model->where('id', $this->model->id)->update(['user_id' => $user_id]);

                //添加系统消息
                foreach ($user_info_arr as $key => $val) {
                    $serviceNoticeSendLogModel = new ServiceNoticeSendLog();
                    $serviceNoticeSendLogModel->add([
                        'notice_id' => $this->model->id,
                        'user_id' => $val['id'],
                        'open_id' => $val['open_id'],
                    ]);
                    $this->systemAdd($data['type_name'], $val['id'], $val['account_id'], 29, $this->model->id, $data['content']);
                }

                $msg = '发送';
                DB::commit(); //先把数据提交

                //异步发送数据
                $url = $this->getHostUrl() . '/admin/serviceNotice/asyncSend';
                request_url($url, ['notice_id' => $this->model->id], 3);

                //  $this->asyncSend($this->model->id);

                // $user_open_id = array_column($user_info_arr, 'open_id');
                // request_url($url, [
                //     'send_data' => [
                //         'notice_id' => $this->model->id,
                //         'time' => $time,
                //         'content' => $data['content'],
                //         'type_name' => $data['type_name'],
                //         'remark' => $data['remark'],
                //         'link' => $data['link'],
                //     ],
                //     'user_open_id' => $user_open_id
                // ], 3);
                //异步发送end

            } else {
                $msg = '保存';
                DB::commit(); //先把数据提交   //单独提交
            }

            return $this->returnApi(200, $msg . '成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }

    /**
     * 服务提醒通知 修改（只有未发送的才可以修改）
     * @param id
     * @param node 是否批量推送   1 批量推送  ， 2 微信限制  3 读者证号限制
     * @param content 内容      必传  最大 100 字
     * @param type_name 服务类型   必传  最大 50 字
     * @param start_time 开始时间  年月日形式  YYYY-mm-dd
     * @param end_time 结束时间   年月日形式  YYYY-mm-dd
     * @param wechat_id 微信昵称id  多个逗号拼接
     * @param account_id 读者证号  多个逗号拼接
     * @param remark 备注     可选  最大 150 字
     * @param link 链接    可选  最大 120 字
     * @param is_send  1 立即发送   2 后续发送
     */
    public function change()
    {
        if (config("other.is_send_wechat_temp_info") !== true) {
            return $this->returnApi(202, '此功能未开通，请联系管理员进行处理！');
        }
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check(array_filter($this->request->all()))) //因为有些是可选参数，如果为空，内置验证也要验证，所以排除掉空数据
        {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $condition[] = ['node', '=', $this->request->node];
        $condition[] = ['type_name', '=', $this->request->type_name];
        $is_exists = $this->model->nameIsExists($this->request->content, 'content', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该内容已存在");
        }

        if ($this->request->node == 2 && empty($this->request->wechat_id)) {
            return $this->returnApi(202, '请选择需要推送的微信昵称！');
        }
        if ($this->request->node == 3 && empty($this->request->account_id)) {
            return $this->returnApi(202, '请选择需要推送的读者证号！');
        }

        set_time_limit(500); // 设置执行不超时


        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();
        if (empty($res)) {
            return $this->returnApi(202, '推送信息不存在');
        }
        if ($res->is_send == 1) {
            return $this->returnApi(202, '此信息已发送不允许修改');
        }
        if ($this->request->end_time) {
            $time = trim($this->request->start_time) . '~' . trim($this->request->end_time);
        } else {
            $time = trim($this->request->start_time);
        }
        $data = $this->request->all();
        unset($data['start_time']);
        unset($data['end_time']);
        $data['type_name'] = addslashes(trim($this->request->type_name));
        $data['content'] = addslashes(trim($this->request->content));
        $data['remark'] = addslashes(trim($this->request->remark));
        $data['link'] = addslashes(trim($this->request->link));
        $data['time'] = $time;
        $data['wechat_id'] = $this->request->node == 2 ? str_replace('，', ',', trim($this->request->wechat_id)) : '';
        $data['account_id'] = $this->request->node == 3 ? str_replace('，', ',', trim($this->request->account_id)) : '';
        DB::beginTransaction();
        try {
            $this->model->change($data);
            if ($this->request->is_send == 1) {
                $userInfoModel = new UserInfo();
                $user_info_arr = $userInfoModel->getUserInfoByWechatAccountId($data['wechat_id'], $data['account_id']);
                $user_id = array_column($user_info_arr, 'id');
                $user_id = join(',', $user_id);
                $this->model->where('id', $data['id'])->update(['user_id' => $user_id]);

                //添加系统消息
                foreach ($user_info_arr as $key => $val) {
                    $serviceNoticeSendLogModel = new ServiceNoticeSendLog();
                    $serviceNoticeSendLogModel->add([
                        'notice_id' => $this->request->id,
                        'user_id' => $val['id'],
                        'open_id' => $val['open_id'],
                    ]);

                    $this->systemAdd($data['type_name'], $val['id'], $val['account_id'], 29, $this->request->id, $data['content']);
                }

                $msg = '发送';
                DB::commit(); //先把数据提交

                //异步发送数据
                $url = $this->getHostUrl() . '/admin/serviceNotice/asyncSend';
                request_url($url, ['notice_id' => $this->request->id], 3);

                // $user_open_id = array_column($user_info_arr, 'open_id');
                // request_url($url, [
                //     'send_data' => [
                //         'notice_id' => $this->request->id,
                //         'time' => $time,
                //         'content' => $data['content'],
                //         'type_name' => $data['type_name'],
                //         'remark' => $data['remark'],
                //         'link' => $data['link'],
                //     ],
                //     'user_open_id' => $user_open_id
                // ], 3);
                //异步发送end

            } else {
                $msg = '保存';
                DB::commit(); //先把数据提交   //单独提交
            }

            return $this->returnApi(200, $msg . '成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 立即发送 服务提醒通知   前端自己设置超时时间，超时未返回数据，则提示提交成功，等待后台发送字样，交由后台自己执行发送操作
     * @param id
     */
    public function send()
    {
        if (config("other.is_send_wechat_temp_info") !== true) {
            return $this->returnApi(202, '此功能未开通，请联系管理员进行处理！');
        }

        //增加验证场景进行验证
        if (!$this->validate->scene('send')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();
        if (empty($res)) {
            return $this->returnApi(201, '参数错误');
        }
        if ($res->is_send == 1) {
            return $this->returnApi(201, '此消息已发送过，不允许再次发送！');
        }

        DB::beginTransaction();
        try {
            $userInfoModel = new UserInfo();
            $user_info_arr = $userInfoModel->getUserInfoByWechatAccountId($res->wechat_id, $res->account_id);
            $user_id = array_column($user_info_arr, 'id');
            $user_id = join(',', $user_id);

            $res->is_send = 1;
            $res->user_id = $user_id;
            $res->save();

            //添加系统消息
            foreach ($user_info_arr as $key => $val) {
                $serviceNoticeSendLogModel = new ServiceNoticeSendLog();
                $serviceNoticeSendLogModel->add([
                    'notice_id' => $res->id,
                    'user_id' => $val['id'],
                    'open_id' => $val['open_id'],
                ]);

                $this->systemAdd($res->type_name, $val['id'], $val['account_id'], 29, $res->id, $res->content);
            }

            DB::commit(); //先把数据提交

            //异步发送数据
            $url = $this->getHostUrl() . '/admin/serviceNotice/asyncSend';
            request_url($url, ['notice_id' => $res->id], 3);

            // $user_open_id = array_column($user_info_arr, 'open_id');
            // request_url($url, [
            //     'send_data' => [
            //         'notice_id' => $res->id,
            //         'time' => $res['time'],
            //         'content' => $res['content'],
            //         'type_name' => $res['type_name'],
            //         'remark' => $res['remark'],
            //         'link' => $res['link'],
            //     ],
            //     'user_open_id' => $user_open_id
            // ], 3);

            return $this->returnApi(200, '推送成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 删除服务提醒通知
     * @param id 服务提醒通知id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('send')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $res = $this->model->where('id', $id)->where('is_del', 1)->first();
        if (empty($res)) {
            return $this->returnApi(201, '参数错误');
        }
        if ($res->is_send == 1) {
            return $this->returnApi(201, '此消息已发送过，不允许删除！');
        }

        $res->is_del = 2;
        $res->change_time = date('Y-m-d H:i:s');
        $result = $res->save();
        if ($result) {
            return $this->returnApi(200, '删除成功', true);
        }
        return $this->returnApi(203, '删除失败');
    }

    /**
     * 异步执行发送消息
     * @param $data 发送数据
     * @param $user_open_id
     */
    public function asyncSend()
    {
        //   return $this->returnApi(201, '参数错误');

        $notice_id = $this->request->notice_id;
        Log::channel('templatepushlog')->debug('接收到发送服务提醒通知消息数据ID：' . $notice_id);

        if (empty($notice_id)) {
            return false;
        }
        $res = $this->model->where('id', $notice_id)->where('is_del', 1)->first();
        if (empty($res)) {
            return $this->returnApi(201, '参数错误');
        }
        $content = $res['content'];
        $type_name = $res['type_name'];
        $link = $res['link'];
        $time = $res['time'];
        $remark = $res['remark'];
        $tempInfoObj = new \App\Http\Controllers\TempInfoController();
        DB::table('service_notice_send_log')->where('notice_id', $notice_id)
            ->where('status', 3)
            ->orderBy('id')
            ->chunkById(100, function ($send_log) use ($tempInfoObj, $content, $type_name, $link, $time, $remark) {
                foreach ($send_log as $val) {
                    $send_data = [];
                    //添加推送模板消息
                    $send_data['content'] = $content;
                    $send_data['type_name'] = $type_name;
                    $send_data['link'] = $link;
                    $send_data['time'] = $time;
                    $send_data['remark'] = $remark;

                    // $send_data['openid'] = $val->open_id;
                    $send_data['openid'] = 'oqYkUuPT6Echdn23R3-gUqKW9_9A';
                    $result = $tempInfoObj->sendServiceInfoV2($send_data);
                    if ($result['errcode'] === 0 && $result['errmsg'] === 'ok') {
                        $status = 1;
                        $reason = '';
                    } else {
                        $status = 2;
                        $reason = $result['errmsg'];
                    }
                    DB::table('service_notice_send_log')
                        ->where('id', $val->id)
                        ->update(['status' => $status, 'reason' => $reason, 'change_time' => date('Y-m-d H:i:s')]);
                }
            });
    }


    /**
     * 异步执行发送消息
     * @param $data 发送数据
     * @param $user_open_id
     */
    public function _asyncSend()
    {

        $data = $this->request->send_data;
        $user_open_id = $this->request->user_open_id;

        Log::channel('templatepushlog')->debug('接收到发送服务提醒通知消息数据：' . $data);
        Log::channel('templatepushlog')->debug('接收到发送服务提醒通知消息推送用户：' . $user_open_id);

        if (empty($data) || empty($user_open_id)) {
            return false;
        }
        $tempInfoObj = new \App\Http\Controllers\TempInfoController();
        $send_data = [];
        foreach ($user_open_id as $key => $val) {
            //添加推送模板消息
            $send_data['content'] = $data['content'];
            $send_data['type_name'] = $data['type_name'];
            $send_data['link'] = $data['link'];
            $send_data['time'] = $data['time'];;

            $send_data['openid'] = $val;
            $tempInfoObj->sendServiceInfoV2($send_data);
        }
    }
}
